﻿using Mongodb;
using ProductTool.Dao;
using ProductTool.Entity;
using ProductTool.Tools;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Text.RegularExpressions;

namespace ProductTool.Service
{
    class ItemService2
    {
        string token = "eyJhdXRoIjoiZTg0OWYxMjM0YWU1ZDg0NzY4ZDMxYTIxNDRhNWYxM2EiLCJkYXRhIjoiMTAwMCIsImV4cCI6MTU1Mjc2MjIwNSwiaXNMb2dpbiI6MSwic2FsdCI6IjE2MDgifQ==";
        ItemDao dao = new ItemDao();
        BrandDao bDao = new BrandDao();
        List<BrandEntity> brandList = new List<BrandEntity>();
        public void Process() {
            brandList = bDao.QueryBrand();
            var list = new List<JDItem>();
            int page = 1;
            do
            {
                list = dao.QueryJdItem(page, 10,"");
                foreach (var item in list)
                {                 
                    var res = createItem(item);
                    while (res == null)
                    {
                        Console.WriteLine("...........service err,retrying......");
                    }
                    if (res.messageId == 10000)
                    {
                        Console.WriteLine($"{item.sku} success");
                    }
                    else
                    {
                        Console.WriteLine($"{item.sku}=>{Newtonsoft.Json.JsonConvert.SerializeObject(res)}");
                    }
                }
                Console.WriteLine($".................page {page} complete.........");
                page++;
            } while (list.Count > 0);
           
            Console.WriteLine("-----------------------all done----------------------------------");
            Console.ReadKey();
        }
        private ResponseBase createItem(JDItem item)
        {
            item.content_desc = string.IsNullOrEmpty(item.content_desc) ? "暂无描述" : item.content_desc;
            ItemEntity entity = new ItemEntity();
            entity.goods_sn = item.sku;
            entity.category_id = item.c3_id;     
            entity.last_cost = item.last_cost.GetValueOrDefault();
            entity.item_upcs = new Upc[] { new Upc { upc=item.upc,is_delete=0,is_unique=1 } };
            entity.upc_code = item.upc;
            if (!string.IsNullOrEmpty(item.publishers) && item.publishers.Length>2)
            {
                entity.brand_id = brandList.FirstOrDefault(p=>p.brand_name==item.publishers).brand_id;
            }
            else
            {
                entity.brand_id = 0;
            }            
            entity.vendor_id = 1;
            entity.manufacturer_part_number = item.isbn;
            entity.itemShortDescList = new ItemShortDesc[] { new ItemShortDesc { title=item.name }, new ItemShortDesc { title = item.name,language_id="en_US" } };
            entity.itemDescList = new ItemDesc[] { new ItemDesc { overview=BuildDescription(item) } };
            entity.pmList = new PM[]{ new PM { pm_id=338,pm_name= "Queenie Wang" } };
            entity.itemPriceList = new ImItemPriceSetting[] { new ImItemPriceSetting {unit_price=item.unit_price.HasValue? item.unit_price.Value:1m } };

            var str = Newtonsoft.Json.JsonConvert.SerializeObject(entity);
            var result=ServiceHelper.CallService<ResponseBase>("http://ecapi.yamicdn.com/im/item/insert", entity,token);
            if (result!=null && result.messageId!=10000)
            {
                Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(result));
            }
            Thread.Sleep(1000);
            return result;
        }

        public void  processToMongo() {
            var data = dao.QueryJdItem(1,10000,"");
            MongoContext mc = new MongoContext();
            var db = mc.DbSet<JDItem>("items");
            db.AddList(data);
            System.Console.WriteLine("jd to mongo导入完成");
            System.Console.ReadKey();
        }
        /// <summary>
        /// 批量上架
        /// </summary>
        public void ProcessOnLine()
        {
       
            var list = new List<ItemEntity>();
            int page = 1;
            int pageSize = 1000;
            do
            {
                list = dao.QueryAllItem(page, pageSize);
                while (OnLineItem(list) == null)
                {
                    Console.WriteLine("...........service err,retrying......");
                }
                Console.WriteLine($"{page * pageSize} success");
                Console.WriteLine($".................page {page} complete.........");
                page++;
            } while (list.Count > 0);

            Console.WriteLine("-----------------------all done----------------------------------");
            Console.ReadKey();           
        }
        public object OnLineItem(List<ItemEntity> list)
        {
            var itemList = list.Select(p=>p.item_number).ToList();
            var entity = new
            {
                status = "A",
                itemList,
                platChannelList = new PlatChannel[1] { new PlatChannel() }
            };
            var result = ServiceHelper.CallService<ResponseBase>("http://ecapi.yamicdn.com/im/item/batchUpdateStatusV2", entity, token);           
            Thread.Sleep(500);
            return result;
        }


        private string GetItemDescription(string title, string content)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("<div  style=\"font: Arial,Verdana;width: 100%; text-align: left;\">");
            sb.Append("<div style=\"overflow: hidden; margin: 0 20px;padding: 20px 0 20px;\">");
            sb.Append("<div>");
            sb.Append(
                    "<span style=\"background: #f25950; width: 105px; height: 25px; line-height: 28px; display: block; color: #fff; position: absolute; font-size: 14px; padding-left: 20px; border-top-left-radius: 0.5em;\">"
                            + title + "</span>");
            sb.Append(
                    "<h3 style=\"padding-top:0;font-size: 14px; line-height: 38px; width: 150px; height: 0px; overflow: hidden; color: #FFF; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 25px solid #f25950; margin: 0px 10px 0 -50px; margin-left: 5px; position: inherit;\"></h3>");
            sb.Append("<div style=\"border-bottom: 3px solid #f25950;\"></div>");
            sb.Append("</div>");
            sb.Append("<div style=\"padding: 18px 10px 0;\">");
            sb.Append("<div style=\"line-height: 24px;\">");
            sb.Append(content);
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }

        public string BuildDescription(JDItem book)
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append(GetPropertyInfo(book));
            sb.Append(GetItemDescription("编辑推荐", book.editer_desc));
            sb.Append(GetItemDescription("内容简介", book.content_desc));
            sb.Append(GetItemDescription("作者简介", book.author_desc));
            sb.Append(GetItemDescription("精彩书评", book.comments));
            sb.Append(GetItemDescription("目录", book.catalogue));
            sb.Append(GetItemDescription("精彩书摘", book.book_abstract));
            if (!string.IsNullOrWhiteSpace(book.introduction))
            {
                string pattern = "<img.*src=(.*?)[^>]*?>";
                // 现在创建 matcher 对象
                string introduction = Regex.Replace(book.introduction, pattern, "");
                sb.Append(GetItemDescription("前言/序言", introduction));
            }
            return sb.ToString().Replace(":", "%3a").Replace("\"", "%22").Replace("'", "%27");
        }
    }
}
